package com.moyq5.spring.boot.app.register.client;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.stereotype.Component;

import com.moyq5.spring.boot.app.register.AppInfo;
import com.moyq5.spring.boot.app.register.AppStore;

/**
 * 监听任务消息
 * @author Moyq5
 * @date 2019年3月1日
 */
@Component("appInfoClientReceiver")
public class AppInfoReceiver {
	private static final String TOPIC = "app/info/to/app";
	
	private final String CLIENT_ID = AppInfoReceiver.class.getSimpleName() + String.valueOf(Math.round(Math.random() * 1e15));
	@Autowired
	private MqttPahoClientFactory clientFactory;
	@Autowired
	private AppInfoHandler appInfoClientHandler;
    @Bean
	public MessageProducer appInfoClientProducer() {
    	
    	AppInfoRegisterClientConfig cfg = AppInfoRegisterClientFactory.getConfig();
    	AppStore store = cfg.getStore();
    	List<AppInfo> apps = store.list();
    	String[] topics = new String[apps.size()];
    	for (int i = 0; i< topics.length; i++) {
    		topics[i] = TOPIC + "/" + apps.get(i).getAppId();
    	}
    	
    	MqttPahoMessageDrivenChannelAdapter adapter = 
				new MqttPahoMessageDrivenChannelAdapter(CLIENT_ID, clientFactory, topics);
		adapter.setCompletionTimeout(5000);
		adapter.setConverter(new DefaultPahoMessageConverter());
		adapter.setQos(0);
		DirectChannel channel = new DirectChannel();
		channel.subscribe(appInfoClientHandler);
		adapter.setOutputChannel(channel);
		
		return adapter;
	}

}
